package com.love.cloud.auth.service.impl;

import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson2.JSON;
import com.love.cloud.admin.api.entity.SysAuthLog;
import com.love.cloud.auth.mapper.SysAuthLogMapper;
import com.love.cloud.auth.service.AsyncAuthService;
import com.love.cloud.common.security.service.MyUser;
import com.love.cloud.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hongdongqu
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AsyncAuthServiceImpl implements AsyncAuthService {
    private final SysAuthLogMapper sysAuthLogMapper;

    @Override
    @Async
    public void saveLoginLog(Authentication authentication, HttpServletRequest request) {
        MyUser user = SecurityUtils.getUser(authentication);
        if(user!=null){
            SysAuthLog sysAuthLog = new SysAuthLog();
            sysAuthLog.setHeadersInfo(request.getHeader(HttpHeaders.AUTHORIZATION));
            sysAuthLog.setCreateId(user.getId());
            sysAuthLog.setCreateName(user.getUserInfo().getSysUser().getName());
            if(authentication.getDetails()!=null){
                sysAuthLog.setParams(JSON.toJSONString(authentication.getDetails()));
            }
            //0表示登录成功
            sysAuthLog.setType("0");
            sysAuthLog.setRemoteAddr(ServletUtil.getClientIP(request));
            sysAuthLog.setRequestUri(URLUtil.getPath(request.getRequestURI()));
            sysAuthLog.setMethod(request.getMethod());
            sysAuthLog.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
            sysAuthLog.setServiceId(getClientId(authentication));
            sysAuthLogMapper.insert(sysAuthLog);
        }
    }

    private String getClientId(Authentication authentication){
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
            return auth2Authentication.getOAuth2Request().getClientId();
        }
        return null;
    }
}
